package com.lanyou.esb.redis.proxy.impl;

import org.springframework.stereotype.Service;

import redis.clients.jedis.Jedis;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.lanyou.esb.common.Constants4Redis;
import com.lanyou.esb.redis.JedisPoolUtils;
import com.lanyou.esb.redis.proxy.base.BaseStrJedisProxy;
import com.lanyou.esb.redis.vo.IfAlarmVo;

/**
 * 接口重复告警Redis操作代理
 * 
 * @author Davey.wu
 */
@Service
public class IfAlarmRepeatJedisProxy extends BaseStrJedisProxy<IfAlarmVo> {
	private static final String UPDATE_SUFFIX = Constants4Redis.SUFFIX_UPDATE;
	private static final String REPEAT_SUFFIX = Constants4Redis.SUFFIX_REPEAT;
	private int UPDATE_TIMEOUT = Constants4Redis.REDIS_TIMEOUT_IF_ALARM_REPEAT_UPDATE;

	public IfAlarmRepeatJedisProxy() {
		this.setTimeOut(Constants4Redis.REDIS_TIMEOUT_IF_ALARM_REPEAT_INTERVAL);
	}

	@Override
	public String generateKey(String target) {
		return target;
	}

	@Override
	public String generateKeyFromObject(IfAlarmVo target) {
		/**
		 * 1，目标系统编码相同；<br>
		 * 2，接口编码相同；<br>
		 * 3，接口版本相同；<br>
		 * 4，调用方系统编码相同；<br>
		 * 5，告警类型相同；<br>
		 * 6，告警等级相同；<br>
		 **/
		StringBuilder builder = new StringBuilder();
		builder.append(target.getSystemCode());
		builder.append(KEY_SEPARATOR);
		builder.append(target.getIfCode());
		builder.append(KEY_SEPARATOR);
		builder.append(target.getIfVersion());
		builder.append(KEY_SEPARATOR);
		builder.append(target.getCallSystemCode());
		builder.append(KEY_SEPARATOR);
		builder.append(target.getAlarmType());
		builder.append(KEY_SEPARATOR);
		builder.append(target.getAlarmLevel());
		builder.append(REPEAT_SUFFIX);
		return builder.toString();
	}

	/**
	 * 更新接口告警
	 * 
	 * @param alarm
	 * @throws JsonProcessingException
	 */
	public void update(IfAlarmVo alarm) throws JsonProcessingException {
		String key = generateKeyFromObject(alarm);
		String upKey = generateUpdateKey(key);
		String json = toJson(alarm);

		Jedis jedis = JedisPoolUtils.getJedis();
		if (jedis == null) {
			return;
		}
		boolean broken = false;
		try {
			jedis.setex(key, this.getTimeOut(), json);
			jedis.setex(upKey, this.UPDATE_TIMEOUT, json);
		} catch (Exception e) {
			broken = true;
		} finally {
			JedisPoolUtils.returnRes(jedis, broken);
		}
	}

	public String generateUpdateKey(IfAlarmVo alarm) {
		return generateKeyFromObject(alarm) + UPDATE_SUFFIX;
	}

	private String generateUpdateKey(String key) {
		return key + UPDATE_SUFFIX;
	}
}
